<?php
class HttpRequest
{
    /**
     * 发送GET请求
     *
     * @param string $url 请求的URL
     * @param array $params 查询参数
     * @return array ['body' => 响应体, 'http_code' => HTTP状态码]
     */
    public function get($url, $params = [])
    {
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        return $this->execute($url);
    }

    /**
     * 发送POST请求
     *
     * @param string $url 请求的URL
     * @param array $data POST数据
     * @return array ['body' => 响应体, 'http_code' => HTTP状态码]
     */
    public function post($url, $data)
    {
        $options = [
            'http' => [
                'method' => "POST",
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                            "Content-Length: " . strlen(http_build_query($data)) . "\r\n",
                'content' => http_build_query($data)
            ]
        ];
        return $this->execute($url, $options);
    }

    /**
     * 执行HTTP请求
     *
     * @param string $url 请求的URL
     * @param array|null $options stream context options
     * @return array ['body' => 响应体, 'http_code' => HTTP状态码]
     */
    private function execute($url, $options = null)
    {
        // 设置默认的HTTP头信息
        $default_options = [
            'http' => [
                'method' => "GET",
                'header' => "User-Agent: PHP"
            ],
            // 对于HTTPS请求，可能需要以下设置以跳过SSL验证（仅开发环境）
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ]
        ];

        // 合并默认选项与传入选项
        $contextOptions = $options ? array_replace_recursive($default_options, $options) : $default_options;
        $context = stream_context_create($contextOptions);

        // 发送请求
        $response = file_get_contents($url, false, $context);

        if ($response === FALSE) {
            return ['body' => 'Error occurred: ' . error_get_last()['message'], 'http_code' => 0];
        }

        // 获取HTTP响应码
        $http_response_header = isset($http_response_header) ? $http_response_header : [];
        preg_match('/\s(\d{3})\s/', $http_response_header[0], $matches);
        $http_code = isset($matches[1]) ? (int)$matches[1] : 0;

        return ['body' => $response, 'http_code' => $http_code];
    }
}
?>